package chen.jia.xin.finalproject.LogView;

import android.app.ActionBar;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import org.litepal.LitePal;
import org.litepal.tablemanager.Connector;
import java.util.ArrayList;
import java.util.List;
import chen.jia.xin.finalproject.BaseActivity;
import chen.jia.xin.finalproject.ForegroundService.MyService;
import chen.jia.xin.finalproject.GetPosition.LocationActivity;
import chen.jia.xin.finalproject.R;
import chen.jia.xin.finalproject.ReadContactors.ContactsActivity;

public class LogActivity extends BaseActivity implements View.OnClickListener{
    //网络状态改变监听器
    private NetworkChangeReceiver networkChangeReceiver;

    private List<User> allUsers;
    private ArrayList<String> allUserName;
    private AutoCompleteTextView accountEdit;
    private EditText passwordEdit;
    private CheckBox checkBox;
    //SharePreference存储
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    //使活动和服务绑定在一起，能管理服务
    private MyService.DownloadBinder downloadBinder;
    //判断天气预报服务是否开启
    private static Boolean foreServiceStart = false;

    //所有按钮
    Button login;
    Button stop_foreground;
    Button create_user;
    FloatingActionButton floatingActionButton;
    //匿名类变量加强活动与服务间亲密关系（参数）
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            downloadBinder.stopDownload();
        }
    };

    //设置ToolBar的菜单项
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }

    //设置每个菜单项的点击功能
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.call:
                Intent intent = new Intent(LogActivity.this, ContactsActivity.class);
                startActivity(intent);
                break;
            case R.id.weatherforcast:
                //开启前台服务
                Intent bindIntent = new Intent(LogActivity.this, MyService.class);
                bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
                foreServiceStart = true;
                break;
            case R.id.paopao:
                //使用定位(百度地图)
                intent = new Intent(LogActivity.this, LocationActivity.class);
                startActivity(intent);
                break;
        }
        return true;
    }

    public void initAllUsers(){
        //在数据库中查询query(初始化数据库中所有用户)，实现AutoComplete
        try {
            accountEdit = findViewById(R.id.account);
            allUsers = LitePal.where().find(User.class);
            allUserName = new ArrayList<>();
            for (User user : allUsers) {
                allUserName.add(user.getUserName());
            }
            final String[] users = allUserName.toArray(new String[0]);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, users);
            accountEdit.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.log_layout);
        //初始化所有用户名,实现AutoComplete
        initAllUsers();
        //设置ToolBar(先隐藏ActionBar)
        ActionBar actionBar = getActionBar();
        if(actionBar != null){
            actionBar.hide();
        }
        android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //注册网络监听器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver,intentFilter);
        //首先创建在sqlite中创建User数据库
        Connector.getDatabase();
        //初始化变量
        passwordEdit = findViewById(R.id.password);
        login = findViewById(R.id.login);
        login.setOnClickListener(this);
        stop_foreground = findViewById(R.id.stop_foreground);
        stop_foreground.setOnClickListener(this);
        create_user = findViewById(R.id.createUser);
        create_user.setOnClickListener(this);
        floatingActionButton = findViewById(R.id.show_message);
        floatingActionButton.setOnClickListener(this);
        //先从文件中读取数据(如果记住密码)
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        checkBox = findViewById(R.id.remember_password);
        boolean isRemembered = preferences.getBoolean("remember_password",false);
        if(isRemembered){
            accountEdit.setText(preferences.getString("account",""));
            passwordEdit.setText(preferences.getString("password",""));
            checkBox.setChecked(true);
        }
        //悬浮按钮
        floatingActionButton.setBackgroundColor(Color.rgb(230, 230, 250));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(networkChangeReceiver != null){
            unregisterReceiver(networkChangeReceiver);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                //点击登录键
                    String account = accountEdit.getText().toString();
                    String password = passwordEdit.getText().toString();
                    List<User> users = null;
                    //在数据库中查询query
                    try {
                        users = LitePal.where("username = ?",account).find(User.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (users.isEmpty()) {
                        Toast.makeText(LogActivity.this, "暂时没有注册用户，请先注册", Toast.LENGTH_SHORT).show();
                    } else if (password.equals(users.get(0).getUserPassword())) {
                        //密码验证通过后
                        editor = preferences.edit();
                        if (checkBox.isChecked()) {
                            //存储数据时要得到editor
                            //要记住是否选择记住密码
                            editor.putString("account", accountEdit.getText().toString());
                            editor.putString("password", passwordEdit.getText().toString());
                            editor.putBoolean("remember_password", true);
                            checkBox.setChecked(true);
                        } else {
                            editor.clear();
                        }
                        editor.apply();
                        Intent intent = new Intent(LogActivity.this, LoadinAnimation.class);
                        //传递数据
                        intent.putExtra("userName", accountEdit.getText().toString());
                        startActivity(intent);
                    } else {
                        Toast.makeText(LogActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();
                    }
                break;

            case R.id.stop_foreground:
                //关闭前台服务
                if (foreServiceStart) {
                    unbindService(serviceConnection);
                }
                foreServiceStart = false;
                break;

            case R.id.createUser:
                //注册用户
                Intent intent = new Intent(LogActivity.this, CreateUserActivity.class);
                startActivity(intent);
                break;

            case R.id.show_message:
                new AlertDialog.Builder(LogActivity.this)
                        .setTitle("使用需知")
                        .setMessage("1.点击手机图标可以拨打手机上的联系人 \n"+"2.点击天气图标可以查看今天的天气预报"
                                +"\n"+"3.点击跑跑卡丁车图标实现定位功能")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener()
                        { @Override public void onClick(DialogInterface dialog, int which) {
                        } }) .create().show();
                break;
        }
    }

    class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //获得系统服务类，专门管理网络连接
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if(networkInfo != null && networkInfo.isConnected()){
                Toast.makeText(context,"网络已启动!",Toast.LENGTH_LONG).show();
                login.setEnabled(true);
                create_user.setEnabled(true);
            }else{
                Toast.makeText(context,"无法连接,网络已关闭!",Toast.LENGTH_LONG).show();
                login.setEnabled(false);
                create_user.setEnabled(false);
            }
        }
    }
}
